package com.example.elysiumease.controller;

import com.example.elysiumease.exception.BusinessException;
import com.example.elysiumease.mapper.SoulMapper;
import com.example.elysiumease.mapper.TrialMapper;
import com.example.elysiumease.model.*;

import com.example.elysiumease.model.enums.PunishmentType;
import com.example.elysiumease.model.enums.TrialStatus;
import com.example.elysiumease.result.JudgmentResult;
import com.example.elysiumease.result.ResponseResult;
import com.example.elysiumease.result.VerdictRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/trials")
@Validated
@Slf4j
public class TrialController {
    //postman测试完成

    @Autowired
    private TrialMapper trialMapper;

    @Autowired
    private SoulMapper soulMapper;

    // 启动审判流程
    @PostMapping("/{soulId}/start")
    @Transactional
    public ResponseResult<Long> startJudgment(
            @PathVariable @Min(1) Integer soulId,
            @RequestParam @Min(1) Integer judgeId) {
        // 校验灵魂状态
        Soul soul = soulMapper.selectById(soulId);
        if (soul == null) {
            throw new BusinessException(404, "灵魂记录不存在");
        }
        if (soul.getCurrentStatus() != Soul.SoulStatus.PENDING) {
            throw new BusinessException("当前状态无法开始审判，需为待审判状态");
        }

        // 创建审判记录
        TrialRecord trial = new TrialRecord();
        trial.setSoulId(soulId);
        trial.setJudgeId(judgeId);
        trial.setStartTime(LocalDateTime.now());
        trial.setStatus(TrialStatus.IN_PROGRESS);

        if (trialMapper.insert(trial) <= 0) {
            throw new BusinessException("审判流程启动失败");
        }

        // 更新灵魂状态
        soul.setCurrentStatus(Soul.SoulStatus.JUDGING);
        soulMapper.update(soul);

        log.info("审判流程启动成功，审判ID：{}", trial.getTrialId());
        return ResponseResult.success(trial.getTrialId());
    }

    // 提交审判结果
    @PostMapping("/{trialId}/verdict")
    @Transactional
    public ResponseResult<Void> submitVerdict(
            @PathVariable @Min(1) Long trialId,
            @Valid @RequestBody VerdictRequest request) {

        // 获取审判记录
        TrialRecord trial = trialMapper.selectById(trialId);
        if (trial == null) {
            throw new BusinessException(404, "审判记录不存在");
        }
        if (trial.getStatus() != TrialStatus.IN_PROGRESS) {
            throw new BusinessException("当前审判状态不可提交结果");
        }

        // 获取关联灵魂
        Soul soul = soulMapper.selectById(trial.getSoulId());
        if (soul == null) {
            throw new BusinessException("关联灵魂记录不存在");
        }

        // 计算最终判决
        JudgmentResult result = calculateJudgment(request);

        // 更新审判记录
        trial.setEndTime(LocalDateTime.now());
        trial.setStatus(TrialStatus.COMPLETED);
        trial.setVerdictDetails(result.getDetails());
        trial.setSentenceDuration(result.getDuration());
        trial.setPunishmentType(result.getPunishmentType());
        trialMapper.update(trial);

        // 更新灵魂状态
        soul.setCurrentStatus(Soul.SoulStatus.JUDGING);
        soul.setPunishmentType(result.getPunishmentType());
        soul.setSentenceDuration(result.getDuration());
        soulMapper.update(soul);

        log.info("审判结果提交成功，审判ID：{}", trialId);
        return ResponseResult.success();
    }

    // 获取审判记录
    @GetMapping("/{trialId}")
    public ResponseResult<TrialRecord> getTrialRecord(
            @PathVariable @Min(1) Long trialId) {
        TrialRecord record = trialMapper.selectById(trialId);
        if (record == null) {
            throw new BusinessException(404, "审判记录不存在");
        }
        return ResponseResult.success(record);
    }

    // 获取灵魂的审判历史
    @GetMapping("/soul/{soulId}")
    public ResponseResult<List<TrialRecord>> getTrialHistory(
            @PathVariable @Min(1) Integer soulId) {
        return ResponseResult.success(trialMapper.selectBySoulId(soulId));
    }

    private JudgmentResult calculateJudgment(VerdictRequest request) {
        JudgmentResult result = new JudgmentResult();

        // 示例判决计算逻辑（根据业务需求实现）
        result.setDuration(calculateSentenceDuration(request));
        result.setPunishmentType(determinePunishment(request));
        result.setDetails(buildVerdictDetails(request));

        return result;
    }

    private int calculateSentenceDuration(VerdictRequest request) {
        // 实际刑期计算逻辑
        return request.getSeverity() * 100;
    }

    private PunishmentType determinePunishment(VerdictRequest request) {
        // 实际惩罚类型判断逻辑
        return request.getRecommendedPunishment();
    }

    private String buildVerdictDetails(VerdictRequest request) {
        return String.format("""
            判决详情：
            - 建议惩罚类型：%s
            - 严重程度评级：%d级
            - 附加说明：%s
            """,
                request.getRecommendedPunishment().getDescription(),
                request.getSeverity(),
                request.getComments());
    }

    // DTO 定义


}